package com.yjd.api.user;

import com.yjd.api.util.PicsResourceUtils;
import com.yjd.api.util.TagUtils;
import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.base.control.MobileBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.CityModel;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.base.service.ICityService;
import com.yjd.comm.order.model.ApplyOrderModel;
import com.yjd.comm.order.model.OrderInterestModel;
import com.yjd.comm.order.model.OrderResult;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.org.model.OrgInfo;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.project.model.PrjCategoryModel;
import com.yjd.comm.project.model.ProjectInteresModel;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.model.ProjectShowInfo;
import com.yjd.comm.project.service.IPrjCategoryService;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.resource.service.IResourceService;
import com.yjd.comm.tag.model.TagInfoDto;
import com.yjd.comm.tag.service.ITagService;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.util.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

/**
 * 快速分期相关
 * Created by yjd-wap on 2017/7/5.
 */

@Controller
@Scope("prototype")
@RequestMapping("/billStages/")
public class BillStagesControl extends MobileBaseControl {

    @Resource
    private ICityService cityService;

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IResourceService resourceService;

    @Resource
    private ITagService tagService;


    @Resource
    private IPrjCategoryService prjCategoryService;

    @Resource
    private IProjectService projectService;

    @Resource
    private IOrderService orderService;

    /**
     * 快速分期 机构列表
     *
     * @throws Exception
     */
    @RequestMapping("orgList")
    public void orgList() throws Exception {
        String cityName = request.getParameter("cityName");
        String cityKey = "31";//默认查上海
        if (!StringUtil.isEmpty(cityName)) {
            CityModel model = cityService.getModelOne(FrameUtil.newHashMap("name", cityName), DbWREnums.READ);
            if (model != null) {
                cityKey = model.getId().toString().substring(0, 2);
            }
        }
        String keys = request.getParameter("keys");
        //本地机构
        List<OrganizationModel> localOrgList = organizationService.getBillStagesOrgListByKeys(FrameUtil.newHashMap("keys", keys, "cityKey", cityKey));

        Map<String, Object> paramMap = FrameUtil.newHashMap("is_used", 1, "sort", " is_spread , org_sort desc ", "page", request.getParameter("page"));
        //热门机构
        PagerModel pagerModel = organizationService.getPageModel(paramMap, DbWREnums.READ);
        List<OrganizationModel> hotOrgList = pagerModel.getDataList();
        pagerModel.setDataList(orgInfoProccesList(hotOrgList));
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("localOrgList", orgInfoProccesList(localOrgList));
        result.put("hotOrgList", pagerModel);
        this.successData(result);
    }

    /**
     * 快速分期 机构信息
     *
     * @throws Exception
     */
    @RequestMapping("orgInfo")
    public void orgInfo(@RequestParam Long org_id) throws Exception {
        if (org_id == null) {
            FrameUtil.throwBaseException1("参数错误");
        }
        OrganizationModel organizationModel = organizationService.getModelById(org_id, DbWREnums.READ);
        organizationModel.setOrg_pic(ServletUtil.getFileUrl(organizationModel.getOrg_pic()));
        List<PrjCategoryModel> list = prjCategoryService.getModelList(null, DbWREnums.READ);
        this.successData(FrameUtil.newHashMap("list", list, "model", organizationModel));
    }

    /**
     * 快速分期 机构 分类项目
     *
     * @throws Exception
     */
    @RequestMapping("prjList")
    public void prjList(@RequestParam Long org_id, @RequestParam Long c_id) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        paramMap.put("rows", "10");
        paramMap.put("is_used", 1);
        paramMap.put("org_id", org_id);
        paramMap.put("category_id", c_id);
        PagerModel pagerModel = projectService.getProjectListByKeys(paramMap);
        List<ProjectShowInfo> prjList = pagerModel.getDataList();
        List<Long> pjIdList = FrameUtil.getBeanFieldValues(prjList, "project_id");
        List<ResourceModel> resourceModelList = null;
        if (pjIdList != null) {
            resourceModelList = resourceService.getModelList(FrameUtil.newHashMap("ref_type", 2, "idList", pjIdList), DbWREnums.READ);
        }
        for (ProjectShowInfo showInfo : prjList) {
            showInfo.setPicsUrl(ServletUtil.getFileUrl(PicsResourceUtils.getPicsList(resourceModelList, showInfo.getProject_id())));//设置项目的图片
        }
        this.successData(FrameUtil.newHashMap("data", prjList));
    }


    /**
     * 加载机构其他信息
     *
     * @param list
     * @return
     * @throws Exception
     */
    private List<OrgInfo> orgInfoProccesList(List<OrganizationModel> list) throws Exception {
        List<OrgInfo> orgInfoList = new ArrayList<OrgInfo>();
        if (list != null && list.size() > 0) {
            List<Long> orgIdList = FrameUtil.getBeanFieldValues(list, "org_id");
            List<TagInfoDto> allTagList = null;
            if (orgIdList != null) {
                allTagList = tagService.getTagNameList(FrameUtil.newHashMap("ref_type", 1, "idList", orgIdList));
            }
            Map<Integer, String> showTypes = TypeShowUtils.getOrgType();
            for (OrganizationModel orgModel : list) {
                OrgInfo orgInfo = new OrgInfo();
                orgInfo.setOrg_id(orgModel.getOrg_id());
                orgInfo.setOrg_name(orgModel.getOrg_name());
                orgInfo.setOrg_address(orgModel.getOrg_address());
                orgInfo.setOrg_type(showTypes.get(orgModel.getOrg_type()));
                orgInfo.setPicsUrl(ServletUtil.getFileUrl(orgModel.getOrg_pic()));//设置机构的图片
                orgInfo.setTagList(TagUtils.getTagNameList(allTagList, orgInfo.getOrg_id()));//设置机构标签
                orgInfoList.add(orgInfo);
            }
        }
        return orgInfoList;
    }

    @RequestMapping("limitList")
    public void limit(Long org_id) throws Exception {

        /**
         * 查询对应的机构
         * 1、机构不存在，返回默认分期配置
         * 2、存在，则返回机构自己的分期配置
         */
        OrganizationModel org = null;
        if (null != org_id) {
            org = organizationService.getModelById(org_id, DbWREnums.READ);
        }

        List<Integer> periodsList = Collections.EMPTY_LIST;
        if (null == org) {
            periodsList = StagesInterestUtils.getMfqPeriodsConfig();
        } else {
            periodsList = StringUtil.getObject(org.getLimit_config(), List.class);
        }

        this.successData(FrameUtil.newHashMap("limitList", periodsList));
    }

    @RequestMapping("interest")
    public void interest(OrderInterestModel model) throws Exception {
        if (model == null || model.getPj_list() == null || model.getLimit() == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }

        Map<Long, ProjectModel> prjMap = projectService.getModelMapByIds(model.getPj_list(), DbWREnums.WRITE);
        List<ProjectInteresModel> list = new ArrayList<ProjectInteresModel>();
        for (Long prj_id : model.getPj_list()) {
            ProjectModel projectModel = prjMap.get(prj_id);
            if (projectModel == null) {
                FrameUtil.throwBaseException1("您选择的项目不存在！");
            }
            ProjectInteresModel interesModel = new ProjectInteresModel();
            interesModel.setProject_id(projectModel.getProject_id());
            interesModel.setLoan_price(projectModel.getLoan_price());
            interesModel.setRate_config(projectModel.getRate_config());
            list.add(interesModel);
        }
        Double repayment = StagesInterestUtils.getAllRepayment(list, model.getLimit());
        //每期还款的金额
        Double limit_price = ArithUtil.round(ArithUtil.div(repayment, model.getLimit()));
        this.successData(FrameUtil.newHashMap("limit_price", limit_price));
    }

    /**
     * 快速分期 提交
     *
     * @param orderModel
     * @throws Exception
     */
    @RequestMapping("submit")
    public void submit(ApplyOrderModel orderModel) throws Exception {
        if (orderModel == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }

        UserSession userSession = super.getUserSession();

        // 账户是否被锁定
        if (1 == userSession.getUser_status()) {
            this.errorMsg("您的账号已被锁定，请联系客服。");
            return;
        }

        OrderResult result = orderService.generateOrder(orderModel, userSession.getUser_id());
        if (result == null) {
            FrameUtil.throwBaseException1("您的申请失败！");
        }
        this.successData(FrameUtil.newHashMap("data", result));
    }


    @RequestMapping("billPotocol")
    public String billPotocol(OrderInterestModel model) throws Exception {
        if (model == null || model.getPj_list() == null || model.getLimit() == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }
        Map<Long, ProjectModel> prjMap = projectService.getModelMapByIds(model.getPj_list(), DbWREnums.WRITE);
        List<ProjectInteresModel> list = new ArrayList<ProjectInteresModel>();
        Double sum_price = 0D;
        for (Long prj_id : model.getPj_list()) {
            ProjectModel projectModel = prjMap.get(prj_id);
            if (projectModel == null) {
                FrameUtil.throwBaseException1("您选择的项目不存在！");
            }
            ProjectInteresModel interesModel = new ProjectInteresModel();
            interesModel.setProject_id(projectModel.getProject_id());
            interesModel.setLoan_price(projectModel.getLoan_price());
            interesModel.setRate_config(projectModel.getRate_config());
            list.add(interesModel);
            sum_price = ArithUtil.add(sum_price, projectModel.getLoan_price());
        }
        Double repayment = StagesInterestUtils.getAllRepayment(list, model.getLimit());
        //每期还款的金额
        Double limit_price = ArithUtil.round(ArithUtil.div(repayment, model.getLimit()));
        request.setAttribute("limit_price", NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
        request.setAttribute("sum_price", NumberUtil.formatNumber(sum_price, NumberUtil.FORMAT_4));
        request.setAttribute("limit", model.getLimit());
        return "user/billProtocol";
    }
}
